import { observable, action } from 'mobx'
import http from 'utils/http'

class ProductStore {
  @observable productList = []
  @observable hotProductList = []
  @observable total = 0
  @observable productInfo = {}
  @observable conditions = {
    money: '',
    loadLimit: '',
    card: '',
    repayType: '',
    order: '',
  }

  /**
   * motion：
   * 上拉加载更多：up 下拉刷新：down
   */
  @action
  async getProductList(payload, motion) {
    const res = await http.get('products/list', payload)
    if (res.code === 1) {
      if (motion === 'up') {
        this.productList = this.productList.concat(res.data.data)
      } else {
        this.productList = res.data.data
      }
      this.total = res.data.total
      return res.data.data
    }
    throw new Error(res.info)
  }

  @action
  async getHotProductList() {
    const res = await http.get('products/list', {
      page: 1,
      pageSize: 30,
      isHot: 1,
    })
    this.hotProductList = res.data.data
  }

  @action
  async getProductById(id) {
    const res = await http.get('products/info', { id })
    this.productInfo = res.data
  }

  @action
  saveConditions(name, val) {
    if (val !== undefined) {
      if (Array.isArray(val)) {
        this.conditions[name] = val[0]
      } else {
        this.conditions[name] = val
      }
    }
    return this.conditions
  }
}

const productStore = new ProductStore()

export default productStore
export { ProductStore }
